package com.lanou3g.mynewstest.module.news.headline;

import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsoluteLayout;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.lanou3g.mynewstest.R;
import com.lanou3g.mynewstest.base.MyBaseFragment;
import com.lanou3g.mynewstest.base.MyLog;
import com.lanou3g.mynewstest.beans.NewsHeadlineBeans;
import com.lanou3g.mynewstest.mydb.DaoMaster;
import com.lanou3g.mynewstest.mydb.DaoSession;
import com.lanou3g.mynewstest.mydb.MyData;
import com.lanou3g.mynewstest.mydb.MyDataDao;
import com.lanou3g.mynewstest.tools.IMyAidlInterface;
import com.lanou3g.mynewstest.tools.MyRequestQueue;
import com.lanou3g.mynewstest.tools.RefreshableView;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.dao.query.QueryBuilder;

/**
 * Created by dllo on 16/1/8.
 */
public class HeadlineFragment extends MyBaseFragment {
    private RecyclerView recyclerView;
    private HeadlineAdapter adapter;
    private NewsHeadlineBeans beans = new NewsHeadlineBeans();
    private RefreshableView refreshableView;
    private int times = 0;
    private LinearLayoutManager manager;
    private ImageView imageView;
    private IMyAidlInterface aidlInterface;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;
    private MyDataDao myDataDao;



    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            aidlInterface = IMyAidlInterface.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    private SQLiteDatabase db;
    private DaoMaster.DevOpenHelper helper;


    @Override
    public void onDestroy() {
        super.onDestroy();
        context.unbindService(connection);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_news_headline, container, false);
        refreshableView = (RefreshableView) view.findViewById(R.id.headline_rf);
        recyclerView = (RecyclerView) view.findViewById(R.id.headline_rv);
        manager = new LinearLayoutManager(context);
        imageView = (ImageView) view.findViewById(R.id.headline_top_iv);

        Intent intent = new Intent();
        intent.setAction("com.lanou.tools.GETLOCATION");
        context.bindService(intent, connection, Context.BIND_AUTO_CREATE);

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recyclerView.scrollToPosition(0);
//                try {
//                    Toast.makeText(context, aidlInterface.getLocation(), Toast.LENGTH_SHORT).show();
//
//                } catch (RemoteException e) {
//                    e.printStackTrace();
//                }
            }
        });
        recyclerView.setLayoutManager(manager);
        recyclerView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL_LIST));

        recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {

            private int getBottom() {
                int bottom = (times + 1) * 21;
                return bottom;
            }

            boolean isShowTop = false;

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

                if (manager.findLastCompletelyVisibleItemPosition() == getBottom()) {
                    if (!isShowTop) {
                        times++;
                        getSecondBean(getURL(times));
                        Toast.makeText(context, "正在加载", Toast.LENGTH_SHORT).show();

                    }
                    isShowTop = true;

                } else {
                    isShowTop = false;
                }

            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
        });

        getBeans(getURL(times));


        refreshableView.setOnRefreshListener(new RefreshableView.PullToRefreshListener() {
            @Override
            public void onRefresh() {
                times = 0;
                getBeans(getURL(times));

                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                refreshableView.finishRefreshing();
            }
        }, 0);


        return view;
    }


    private String getURL(int times) {
        String url = "http://c.3g.163.com/nc/article/headline/T1348647909107/" + times * 20 + "-20.html";
        return url;
    }

    private void getBeans(String url) {
        StringRequest request = new StringRequest(url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Gson gson = new Gson();
                        putIn("headline", response);
                        beans = gson.fromJson(response, NewsHeadlineBeans.class);
                        adapter = new HeadlineAdapter(context, beans);
                        recyclerView.setAdapter(adapter);

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                        Gson gson = new Gson();
                        beans = gson.fromJson(getResponse("headline"), NewsHeadlineBeans.class);
                        adapter = new HeadlineAdapter(context, beans);
                        recyclerView.setAdapter(adapter);

                    }
                });
        //单例模式的requestqueue
        MyRequestQueue.addRequest(request);
    }

    private void getSecondBean(String url) {
        StringRequest request = new StringRequest(url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Gson gson = new Gson();
                        NewsHeadlineBeans secondBean = gson.fromJson(response, NewsHeadlineBeans.class);
                        List<NewsHeadlineBeans.T1348647909107Entity> data = secondBean.getT1348647909107();
                        data.remove(0);
                        beans.getT1348647909107().addAll(data);
                        adapter.addData(beans);
                        Toast.makeText(context, "加载成功", Toast.LENGTH_SHORT).show();


                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        //单例模式的requestqueue
        MyRequestQueue.addRequest(request);
    }

    public void putIn(String name, String response) {
        helper = new DaoMaster.DevOpenHelper(context, "MyDB.db", null);
        db = helper.getWritableDatabase();
        mDaoMaster = new DaoMaster(db);
        mDaoSession = mDaoMaster.newSession();
        myDataDao = mDaoSession.getMyDataDao();

        MyData myData = new MyData(name, response);
        myDataDao.insertOrReplace(myData);
    }

    public String getResponse(String name) {
        helper = new DaoMaster.DevOpenHelper(context, "MyDB.db", null);
        db = helper.getWritableDatabase();
        mDaoMaster = new DaoMaster(db);
        mDaoSession = mDaoMaster.newSession();
        QueryBuilder queryBuilder = mDaoSession.getMyDataDao().queryBuilder();
        queryBuilder.where(MyDataDao.Properties.Name.eq(name));
        ArrayList<MyData> datas = (ArrayList<MyData>) queryBuilder.list();
        return datas.get(0).getResponse();
    }
}
